package com.zhilianbao.leyaogo.ui.fragment.shoppingcart;

import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bql.animationcheckbox.AnimationCheckBox;
import com.bql.convenientlog.CLog;
import com.bql.fragmentation.anim.DefaultHorizontalAnimator;
import com.bql.fragmentation.anim.FragmentAnimator;
import com.bql.pulltorefreshandloadmore.loadmoreview.LoadMoreRecyclerView;
import com.bql.utils.CheckUtils;
import com.bql.utils.EventManager;
import com.bql.utils.NumberUtlis;
import com.bql.utils.ThreadPool;
import com.zhilianbao.leyaogo.R;
import com.zhilianbao.leyaogo.alipay.AliPayUtil;
import com.zhilianbao.leyaogo.alipay.IPayCallBack;
import com.zhilianbao.leyaogo.app.LeYaoGoApplication;
import com.zhilianbao.leyaogo.constants.HttpConfig;
import com.zhilianbao.leyaogo.constants.IntentConfig;
import com.zhilianbao.leyaogo.constants.PayConfig;
import com.zhilianbao.leyaogo.events.LeEventCode;
import com.zhilianbao.leyaogo.http.api.AccountApi;
import com.zhilianbao.leyaogo.http.api.AddressApi;
import com.zhilianbao.leyaogo.http.api.CouponApi;
import com.zhilianbao.leyaogo.http.api.OrderApi;
import com.zhilianbao.leyaogo.http.api.PayApi;
import com.zhilianbao.leyaogo.http.callback.DialogCallback;
import com.zhilianbao.leyaogo.http.callback.JsonCallback;
import com.zhilianbao.leyaogo.model.response.Coupon.CanUseCard;
import com.zhilianbao.leyaogo.model.response.Coupon.CanUseCoupon;
import com.zhilianbao.leyaogo.model.response.address.Address;
import com.zhilianbao.leyaogo.model.response.me.MyOrderResponse;
import com.zhilianbao.leyaogo.model.response.shoppingcart.Express;
import com.zhilianbao.leyaogo.model.response.shoppingcart.MyBalance;
import com.zhilianbao.leyaogo.model.response.shoppingcart.PayWay;
import com.zhilianbao.leyaogo.model.response.shoppingcart.ShoppingCartGood;
import com.zhilianbao.leyaogo.model.response.shoppingcart.WXPay;
import com.zhilianbao.leyaogo.ui.activity.me.moneyaccount.BalanceActivity;
import com.zhilianbao.leyaogo.ui.activity.me.myorder.OrderDetailActivity;
import com.zhilianbao.leyaogo.ui.activity.me.setting.SetPwdActivity;
import com.zhilianbao.leyaogo.ui.adapter.shoppingcart.PayOrderGoodsAdapter;
import com.zhilianbao.leyaogo.ui.fragment.address.ModifyAddressFragment;
import com.zhilianbao.leyaogo.ui.fragment.address.ReceiveAddressFragment;
import com.zhilianbao.leyaogo.ui.fragment.base.BaseOkHttpFragment;
import com.zhilianbao.leyaogo.utils.Utils;
import com.zhilianbao.leyaogo.utils.WXPayUtils;
import com.zhilianbao.leyaogo.utils.XTipsDialog;
import com.zhilianbao.leyaogo.utils.XToastUtils;
import com.zhilianbao.leyaogo.view.dialog.CardDialog;
import com.zhilianbao.leyaogo.view.dialog.CommonDialog;
import com.zhilianbao.leyaogo.view.dialog.ConfirmPayDialog;
import com.zhilianbao.leyaogo.view.dialog.CouponDialog;
import com.zhilianbao.leyaogo.view.dialog.PayTypeSelectDialog;
import com.zhilianbao.leyaogo.view.widgets.MoneyTextView;
import com.zhilianbao.leyaogo.view.widgets.SelectPayMethodView;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import okhttp3.Call;
import okhttp3.Response;


/**
 * Author: hcy
 * Description:填写订单 去支付Fragment
 * Created: 2016/10/24 11:00
 */
public class PayOrderFragment extends BaseOkHttpFragment implements View.OnClickListener {

    //HeaderView
    private TextView mReceiveNameTv, mReceivePhoneTv, mReceiveAddressTv, mReceiveTimeTv;//收货人，电话，地址,送货时间
    private LinearLayout mNoDefaultView, mReceiveTimeView;
    private RelativeLayout mAddressView;
    //FooterView
    private MoneyTextView mGoodsTotalPrice, mExpressPrice, mCouponPrice, mCardPrice, mActivityPrice, mTotalPrice;//总金额，运费，优惠抵扣,卡券抵扣,活动抵扣，最终价格
    private TextView mCouponTicketTv, mCardTicketTv, mInvoiceTv;//优惠券，卡券，发票
    private SelectPayMethodView mSelectPayMethodView;//支付方式

    @BindView(R.id.tv_real_pay)
    public MoneyTextView mRealPayTv;

    @BindView(R.id.tv_go_pay)
    public TextView mGoPayTv;

    @BindView(R.id.rcv_load_more)
    public LoadMoreRecyclerView mLoadMoreRecyclerView;

    private View mHeaderView, mFooterView;

    private long useId, supplierId = 1237;

    private ConfirmPayDialog confirmPayDialog;
    private PayTypeSelectDialog payTypeSelectDialog;
    private CouponDialog mCouponDialog;

    private List<ShoppingCartGood> mGoodListData = new ArrayList<>();//购买商品数据
    private List<String> mParamsList = new ArrayList<>();//拼接的请求参数
    private Address mAddress;
    private String activityJSON = "";//商品id，skuId,购买数量拼接，活动json
    private boolean freeExpressActivity;//有没有满包邮的活动
    private List<CanUseCoupon> mCanUseCouponList = new ArrayList<>();//可用优惠券
    private List<CanUseCard> mCanUseCardList = new ArrayList<>();//可用卡券

    private TextView mCouponMinusTv, mCreditsMinusTv, mActivityMinusTv;//抵扣前减号（为0隐藏）

    private double goodTotalPrice = 0.00, expressPrice = 0.00, couponPrice = 0.00,
            cardPrice = 0.00, activityPrice = 0.00, tempActivityPrice = 0.0, finalPrice = 0.00;//商品总价，快递费，优惠券，卡券，活动抵扣，最终价格
    private double shopFreePrice;//超出该金额免运费 大于0才表示该值有效 ,
    private long couponsItemId;//优惠券id
    private String cardItemId;//卡券id， 多个以逗号隔开
    private boolean defaultAddressOK = true;//默认地址是否支持配送
    private boolean haveAddress;//是否有默认地址,是否有地址数据
    private boolean isNoLimitCoupon;//当前使用的优惠券是不是无限制使用的现金券
    private double originalCardPrice, originalCouponPrice;//实际选取的卡券价格,实际选取的优惠价格

    private int mPayType;//底部支付方式

    private MyOrderResponse mAddedOrderInfo;//生成的订单信息

    private MyBalance mMyBalance;//账户余额信息

    private int mDialogPayType = PayConfig.WX_PAY;//对话框支付方式

    private double needToPayPrice;//需付款

    private boolean checkBoxState = true;//余额抵扣选中状态

    private InvoiceFragment.Invoice invoice;//发票记录


    public static PayOrderFragment getInstance(Bundle bundle) {
        PayOrderFragment fragment = new PayOrderFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.fragment_pay_order;
    }

    @Override
    protected void initToolbarHere() {
        initToolbar(getString(R.string.fill_order));
    }

    @Override
    protected void initViewsAndEvents(Bundle savedInstanceState) {
        useId = Utils.getUserLoginInfo().getUserId();
        mPayType = Utils.getLastPayType();
        supplierId = Utils.getSupplierId();
        Bundle bundle = getArguments();
        if (bundle != null) {
            List<ShoppingCartGood> list = bundle.getParcelableArrayList(IntentConfig.SHOPPING_CART_SELECT_DATA);
            if (list != null) {
                mGoodListData.addAll(list);//商品list
            }
            List<String> params = bundle.getStringArrayList(IntentConfig.SHOPPING_CART_PARAMS);
            if (params != null) {
                mParamsList.addAll(params);//
            }

            goodTotalPrice = bundle.getDouble(IntentConfig.SHOPPING_CART_TOTAL_PRICE, 0.0);//总价格
            shopFreePrice = bundle.getDouble(IntentConfig.SHOPPING_CART_SHOP_FREE_PRICE, 0.0);//店铺活动满足该价格包邮（大于0有效）
            activityJSON = bundle.getString(IntentConfig.SHOPPING_CART_ACTIVITY_JSON);//活动拼接json
            freeExpressActivity = bundle.getBoolean(IntentConfig.SHOPPING_CART_FREE_EXPRESS, false);//是否有满足包邮活动的商品
            tempActivityPrice = activityPrice = bundle.getDouble(IntentConfig.SHOPPING_CART_ACTIVITY_DISCOUNT);//活动抵扣金额
        }

        initFooterView();
        initHeaderView();
        mGoPayTv.setOnClickListener(this);

        mLoadMoreRecyclerView.setLayoutManager(new LinearLayoutManager(mActivity));
        mLoadMoreRecyclerView.setAdapter(new PayOrderGoodsAdapter(mActivity, mGoodListData));

        if (freeExpressActivity) {//有满足包邮活动的商品
            expressPrice = 0.00;
        }

        mGoodsTotalPrice.setAmount(goodTotalPrice);//设置商品总价
        mActivityPrice.setAmount(activityPrice);//设置活动优惠价格
        mInvoiceTv.setText(getString(R.string.invoice_not_need));//默认显示不需要发票

        calculateFinalPrice(); //计算价格
        mAddress = Utils.getDefaultAddress();
        CLog.i("hcy", "mAddress=" + mAddress);
        if (mAddress != null) {
            CLog.i("hcy", "mAddress.getAdName()=" + mAddress.getAdName());
        }
        if (CheckUtils.isNull(mAddress)) {
            getDefaultAddress();
        } else {
            getExpress(true, false);
            setAddressData();
        }
        getSupplierPayType();
        getCanUseCoupon();
        getMyRechargeCard();
    }

    /**
     * 初始化HeadView
     */
    private void initHeaderView() {
        mHeaderView = LayoutInflater.from(mActivity).inflate(R.layout.layout_pay_order_header, null);
        mReceiveNameTv = (TextView) mHeaderView.findViewById(R.id.tv_name);
        mReceivePhoneTv = (TextView) mHeaderView.findViewById(R.id.tv_phone);
        mReceiveAddressTv = (TextView) mHeaderView.findViewById(R.id.tv_address);
        mReceiveTimeTv = (TextView) mHeaderView.findViewById(R.id.tv_receive_time);
        mNoDefaultView = (LinearLayout) mHeaderView.findViewById(R.id.view_select_address);
        mNoDefaultView.setOnClickListener(this);
        mAddressView = (RelativeLayout) mHeaderView.findViewById(R.id.view_address);
        mAddressView.setOnClickListener(this);
        mReceiveTimeView = (LinearLayout) mHeaderView.findViewById(R.id.view_deliver_time);
        mLoadMoreRecyclerView.addHeaderView(mHeaderView);
    }

    /**
     * 初始化FooterView
     */
    private void initFooterView() {
        mFooterView = LayoutInflater.from(mActivity).inflate(R.layout.layout_pay_order_footer_view, null);
        mGoodsTotalPrice = (MoneyTextView) mFooterView.findViewById(R.id.tv_pay_goods_total);
        mExpressPrice = (MoneyTextView) mFooterView.findViewById(R.id.tv_pay_logistic);
        mCouponPrice = (MoneyTextView) mFooterView.findViewById(R.id.tv_coupon);
        mCardPrice = (MoneyTextView) mFooterView.findViewById(R.id.tv_credits);
        mActivityPrice = (MoneyTextView) mFooterView.findViewById(R.id.tv_balance);
        mTotalPrice = (MoneyTextView) mFooterView.findViewById(R.id.tv_pay_total);
        mCouponMinusTv = (TextView) mFooterView.findViewById(R.id.tv_coupon_minus);
        mCreditsMinusTv = (TextView) mFooterView.findViewById(R.id.tv_credits_minus);
        mActivityMinusTv = (TextView) mFooterView.findViewById(R.id.tv_balance_minus);

        mCouponTicketTv = (TextView) mFooterView.findViewById(R.id.tv_coupon_ticket);
        mCardTicketTv = (TextView) mFooterView.findViewById(R.id.tv_card_ticket);
        mInvoiceTv = (TextView) mFooterView.findViewById(R.id.tv_invoice);

        mSelectPayMethodView = (SelectPayMethodView) mFooterView.findViewById(R.id.view_pay_method);
        mSelectPayMethodView.setPayMethod(mPayType);

        mFooterView.findViewById(R.id.view_coupon).setOnClickListener(this);
        mFooterView.findViewById(R.id.view_card).setOnClickListener(this);
        mFooterView.findViewById(R.id.view_invoice).setOnClickListener(this);
        mLoadMoreRecyclerView.addFooterView(mFooterView);

        mCardTicketTv.setText(getString(R.string.pl_select));
        mCouponTicketTv.setText(getString(R.string.pl_select));
        //是否活动抵扣减号隐藏减号
        mActivityMinusTv.setVisibility(activityPrice == 0 ? View.GONE : View.VISIBLE);
    }


    /**
     * 获取运营商支付方式
     */
    private void getSupplierPayType() {
        PayApi.getPayWayList(mActivity, Utils.getSupplierId(), 1, new JsonCallback<List<PayWay>>(mActivity) {
            @Override
            public void onSuccess(List<PayWay> payWayList, Call call, Response response) {

            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                showGetPayWayFailDialog();
            }
        });
    }

    /**
     * 设置地址数据
     */
    private void setAddressData() {
        if (mAddress != null) {//有默认地址
            mAddressView.setVisibility(View.VISIBLE);
            mNoDefaultView.setVisibility(View.GONE);
            mReceiveNameTv.setText(mAddress.getAdName());
            mReceivePhoneTv.setText(mAddress.getAdPhone());
            mReceiveAddressTv.setText(mAddress.getStrAddress());
        } else {
            mAddressView.setVisibility(View.GONE);
            mNoDefaultView.setVisibility(View.VISIBLE);
        }

    }

    /**
     * 计算最终价格
     */
    private void calculateFinalPrice() {
        finalPrice = NumberUtlis.add(goodTotalPrice, expressPrice);//商品总价+运费
        finalPrice = NumberUtlis.sub(finalPrice, couponPrice);//
        finalPrice = NumberUtlis.sub(finalPrice, cardPrice);//
        finalPrice = NumberUtlis.sub(finalPrice, activityPrice);//
        if (finalPrice < 0) {
            finalPrice = 0.00;
        }
        mTotalPrice.setAmount(finalPrice);
        mRealPayTv.setAmount(finalPrice);
        //是否要隐藏减号
        mCouponMinusTv.setVisibility(couponPrice == 0 ? View.GONE : View.VISIBLE);
        mCreditsMinusTv.setVisibility(cardPrice == 0 ? View.GONE : View.VISIBLE);
    }

    /**
     * 计算不包括卡券的最终价格
     */
    private double getExcludeCardFinalPrice() {
        double price;
        price = NumberUtlis.add(goodTotalPrice, expressPrice);//商品总价+运费
        price = NumberUtlis.sub(price, couponPrice);//
        price = NumberUtlis.sub(price, activityPrice);//
        if (price < 0) {
            price = 0;
        }
        return price;
    }

    /**
     * 计算不包括优惠券的最终价格
     */
    private double getExcludeCouponFinalPrice() {
        double price;
        price = NumberUtlis.add(goodTotalPrice, expressPrice);//商品总价+运费
        price = NumberUtlis.sub(price, cardPrice);//
        price = NumberUtlis.sub(price, activityPrice);//
        if (price < 0) {
            price = 0;
        }
        return price;
    }

    /**
     * 计算不包括卡券,邮费的最终价格
     */
    private double getExcludeCardExpressFinalPrice() {
        double price = goodTotalPrice;
        price = NumberUtlis.sub(price, couponPrice);//减去
        price = NumberUtlis.sub(price, activityPrice);//
        if (price < 0) {
            price = 0;
        }
        return price;
    }

    /**
     * 如果没有满足包邮活动的商品，计算不包括卡券的总价是否大于shopFreePrice(不为0有效),大于也是包邮
     */
    private void totalPriceMatchShopFreePrice() {
        double totalPrice = getExcludeCardExpressFinalPrice();
        if (!freeExpressActivity && shopFreePrice != 0 && totalPrice >= shopFreePrice) {//满足包邮条件
            activityPrice = NumberUtlis.add(activityPrice, expressPrice);
            mActivityPrice.setAmount(activityPrice);//设置活动优惠价格
            mExpressPrice.setAmount(String.valueOf(expressPrice));
            //是否活动抵扣减号隐藏减号
            mActivityMinusTv.setVisibility(activityPrice == 0 ? View.GONE : View.VISIBLE);
        }
    }

    /**
     * 获取默认地址
     */
    private void getDefaultAddress() {
        AddressApi.getAddress(mActivity, useId, supplierId, 0, new DialogCallback<List<Address>>(mActivity) {
            @Override
            public void onSuccess(List<Address> addresses, Call call, Response response) {

                if (addresses != null && addresses.size() > 0) {
                    haveAddress = true;//有数据
                    for (Address address : addresses) {
                        if (address.getIsDefault() == 1) {//有默认地址
                            mAddress = address;
                            Utils.putDefaultAddress(mAddress);
                            break;
                        }
                    }
                } else {
                    haveAddress = false;
                }
                getExpress(true, false);
                setAddressData();
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                setAddressData();
            }
        });
    }

    /**
     * 获取可用优惠券
     */
    private void getCanUseCoupon() {
        long useId = Utils.getUserLoginInfo().getUserId();
        if (mParamsList.size() < 3) {
            return;
        }
        double amountPrice = NumberUtlis.sub(goodTotalPrice, activityPrice);
        if (amountPrice <= 0) {//价格0不请求优惠券
            mCouponTicketTv.setText(getString(R.string.pl_select));
            return;
        }
        CouponApi.getCanUseCouponList(mActivity, mParamsList.get(0), mParamsList.get(1), mParamsList.get(2), useId, amountPrice, new DialogCallback<List<CanUseCoupon>>(mActivity) {
            @Override
            public void onSuccess(List<CanUseCoupon> canUseCoupons, Call call, Response response) {
                if (canUseCoupons == null || canUseCoupons.size() == 0) {
                    //                    mCouponTicketTv.setText(getString(R.string.no_coupon));
                } else {
                    mCanUseCouponList.addAll(canUseCoupons);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                mCouponTicketTv.setText(getString(R.string.get_error));
            }
        });

    }

    /**
     * 获取卡券
     */
    private void getMyRechargeCard() {
        AccountApi.getMyCardVoucherList(mActivity, useId, supplierId, 1, 0, 0, new DialogCallback<List<CanUseCard>>(mActivity) {

            @Override
            public void onSuccess(List<CanUseCard> canUseCard, Call call, Response response) {
                if (canUseCard == null || canUseCard.size() == 0) {
                    //                    mCardTicketTv.setText(getString(R.string.no_coupon));
                } else {
                    mCanUseCardList.addAll(canUseCard);
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
                mCardTicketTv.setText(getString(R.string.get_error));
            }
        });
    }

    /**
     * 配送判断详细说明
     */
    private void getExpress(boolean isDefault, boolean isModify) {
        if (mAddress == null || mGoodListData.size() == 0) {
            return;
        }
        long shopId = mGoodListData.get(0).getShopId();
        OrderApi.express(mActivity, Utils.getUserLoginInfo().getUserId(), supplierId, mAddress.getAddressId(), shopId, new DialogCallback<Express>(mActivity, true) {

            @Override
            public void onSuccess(Express express, Call call, Response response) {
                if (CheckUtils.isNull(express)) {//失败
                    XToastUtils.showShortToast(getString(R.string.express_error));
                    expressPrice = 0.00;
                    mReceiveTimeTv.setText(String.valueOf(expressPrice));
                    return;
                } else if (!express.isExpress()) {//不在配送范围
                    expressPrice = 0.00;
                    mExpressPrice.setAmount(String.valueOf(express.getExpressPrice()));
                    mReceiveTimeView.setVisibility(View.GONE);
                    //第一进来默认，地址不支持配送，不显示去选择地址弹框
                    if (isDefault) {
                        defaultAddressOK = false;
                    } else {
                        if (!isModify) {//不是修改地址
                            showAddressNotExpress();
                        }
                    }
                }
                if (CheckUtils.isEmpty(express.getComments())) {
                    mReceiveTimeView.setVisibility(View.GONE);
                } else {
                    mReceiveTimeView.setVisibility(View.VISIBLE);
                    mReceiveTimeTv.setText(express.getComments());
                }
                //                if (express.getExpressPrice() != 0) {//活动没有没有满足包邮
                expressPrice = express.getExpressPrice();

                //商品中有满包邮的商品 则该订单包邮
                if (freeExpressActivity) {
                    activityPrice = tempActivityPrice;
                    activityPrice = NumberUtlis.add(activityPrice, expressPrice);
                    //是否活动抵扣减号隐藏减号
                    mActivityMinusTv.setVisibility(activityPrice == 0 ? View.GONE : View.VISIBLE);
                    mActivityPrice.setAmount(activityPrice);//设置活动优惠价格
                    //                    expressPrice = 0.0;
                }


                totalPriceMatchShopFreePrice();//是否满足总价大于店铺活动包邮条件

                noLimitCouponCalculate();//重新计算优惠券抵扣
                calculateCardPriceDiscount();//重新计算卡券抵扣
                //重新计算价格
                calculateFinalPrice();


                //                }
                mExpressPrice.setAmount(String.valueOf(expressPrice));
                if (!defaultAddressOK) {
                    defaultAddressOK = true;
                }
            }

            @Override
            public void onError(Call call, Response response, Exception e) {
                super.onError(call, response, e);
            }

            @Override
            public Express convertSuccess(Response response) throws Exception {
                return Utils.parseExpressJson(response, mActivity);
            }

            @Override
            public boolean dismissDialog() {
                return super.dismissDialog();
            }
        });
    }

    /**
     * 邮费改变后重新计算优惠抵扣
     */
    private void noLimitCouponCalculate() {
        CLog.i("hcy", "isNoLimitCoupon=" + isNoLimitCoupon);
        if (!isNoLimitCoupon) {//
            return;
        }
        double price = getExcludeCouponFinalPrice();
        CLog.i("hcy", "noLimitCouponCalculate------price----------=" + price);
        if (originalCouponPrice >= price) {//大于支付价格
            couponPrice = price;
        }
        mCouponPrice.setAmount(String.valueOf(couponPrice));
    }

    /**
     * 生成订单
     */
    private void addOrder() {
        if (mAddress == null) {
            XToastUtils.showShortToast(getString(R.string.pay_select_address));
            return;
        }
        if (!defaultAddressOK) {//默认地址不支持配送
            showAddressNotExpress();
            return;
        }
        if (mAddedOrderInfo == null) {
            int hasInvoice = 0;//0不需要开发票，1需要
            if (invoice != null && invoice.type != -1) {
                hasInvoice = 1;
            }
            String invoiceTitle = hasInvoice == 0 ? "" : invoice.invoiceTitle;
            int invoiceTitleType = hasInvoice == 0 ? -1 : invoice.type;
            OrderApi.addOrder(mActivity, Utils.getUserLoginInfo().getUserId(), mParamsList.get(0), mParamsList.get(1), mParamsList.get(2),
                    mAddress.getAddressId(), 0, activityJSON, 0, couponsItemId, cardItemId, hasInvoice, 0, invoiceTitle, invoiceTitleType,
                    new DialogCallback<MyOrderResponse>(mActivity, getString(R.string.submitting_order)) {
                        @Override
                        public void onSuccess(MyOrderResponse o, Call call, Response response) {
                            EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ADD_ORDER));
                            mAddedOrderInfo = o;
                            CLog.i("hcy", "mAddedOrderInfo price=" + mAddedOrderInfo.getPaymentPrice());
                            //                            XToastUtils.showShortToast(getString(R.string.submit_order_suc));
                            //                            if (finalPrice == 0) {
                            //                                start(PaySuccessFragment.getInstance(o.getOrderId()));
                            //                            } else {
                            //                                if (mSelectPayMethodView.getPayMethod() == PayConfig.WX_PAY) {
                            //                                    invokeWXPay(o, o.getPaymentPrice(), null);
                            //                                } else if (mSelectPayMethodView.getPayMethod() == PayConfig.ALI_PAY) {
                            //                                    invokeAliPay(o, o.getPaymentPrice(), null);
                            //                                } else if (mSelectPayMethodView.getPayMethod() == PayConfig.YUE_PAY) {
                            //                                    useMyBalancePay(o);
                            //                                }
                            //                            }
                            XTipsDialog.showSuccess(mActivity, getString(R.string.submit_order_suc),
                                    () -> {
                                        if (finalPrice == 0) {
                                            start(PaySuccessFragment.getInstance(o.getOrderId()));
                                        } else {
                                            if (mSelectPayMethodView.getPayMethod() == PayConfig.WX_PAY) {
                                                invokeWXPay(o, o.getPaymentPrice(), null);
                                            } else if (mSelectPayMethodView.getPayMethod() == PayConfig.ALI_PAY) {
                                                invokeAliPay(o, o.getPaymentPrice(), null);
                                            } else if (mSelectPayMethodView.getPayMethod() == PayConfig.YUE_PAY) {
                                                useMyBalancePay(o);
                                            }
                                        }

                                    });

                        }
                    });
        } else {
            if (finalPrice == 0) {
                start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
            } else {
                if (mSelectPayMethodView.getPayMethod() == PayConfig.WX_PAY) {
                    invokeWXPay(mAddedOrderInfo, mAddedOrderInfo.getPaymentPrice(), null);
                } else if (mSelectPayMethodView.getPayMethod() == PayConfig.ALI_PAY) {
                    invokeAliPay(mAddedOrderInfo, mAddedOrderInfo.getPaymentPrice(), null);
                } else if (mSelectPayMethodView.getPayMethod() == PayConfig.YUE_PAY) {
                    useMyBalancePay(mAddedOrderInfo);
                }
            }

        }

    }

    /**
     * 调用余额支付
     *
     * @param orderInfo 订单消息
     */
    private void useMyBalancePay(MyOrderResponse orderInfo) {
        PayApi.getMyBalance(mActivity, orderInfo.getSupplierId(), orderInfo.getUserId(), new DialogCallback<MyBalance>(mActivity, getString(R.string.get_available_balance)) {
            @Override
            public void onSuccess(MyBalance balance, Call call, Response response) {
                mDialogPayType = PayConfig.WX_PAY;
                mMyBalance = balance;
                checkBoxState = true;
                needToPayPrice = NumberUtlis.sub(orderInfo.getPaymentPrice(), balance.getAvailableBalance());
                //余额足够  全余额支付 首先要判断是否设置了支付密码
                if (balance.getAvailableBalance() >= orderInfo.getPaymentPrice()) {
                    ThreadPool.postOnUiDelayed(() ->
                                    PayApi.hasSetPayPwd(mActivity, new DialogCallback<String>(mActivity, getString(R.string.verify_pay_environment)) {
                                        @Override
                                        public void onSuccess(String o, Call call, Response response) {
                                            if (CheckUtils.equalsString(o, HttpConfig.MSG_ERROR_CODE_10046 + "")) {
                                                XToastUtils.showShortToast(getString(R.string.set_pay_pwd_first));
                                                Utils.startActivity(mActivity, SetPwdActivity.class);
                                                //                                                XTipsDialog.showFail(mActivity, getString(R.string.set_pay_pwd_first), () -> Utils.startActivity(mActivity, SetPwdActivity.class));
                                            } else {
                                                start(PayByBalanceFragment.getInstance(mAddedOrderInfo));
                                            }

                                        }


                                    })
                            , 300);

                }
                //余额为0  提示充值对话框
                else if (balance.getAvailableBalance() == 0) {
                    showGoToChargeDialog();
                }
                //余额不足结合第三方支付平台支付
                else {
                    needToPayPrice = NumberUtlis.sub(orderInfo.getPaymentPrice(), balance.getAvailableBalance());
                    //                    XToastUtils.showShortToast(getString(R.string.balance_not_enough));
                    //                    showPayDetailDialog(mDialogPayType, orderInfo.getPaymentPrice(), balance.getAvailableBalance(), needToPayPrice, checkBoxState);
                    XTipsDialog.showFail(mActivity, getString(R.string.balance_not_enough), () -> showPayDetailDialog(mDialogPayType, orderInfo.getPaymentPrice(), balance.getAvailableBalance(), needToPayPrice, checkBoxState));
                }
            }
        });
    }


    /**
     * 调用微信支付
     *
     * @param orderInfo        订单消息
     * @param paymentPrice     需付款
     * @param availableBalance 可用余额 混合支付用到
     */
    private void invokeWXPay(MyOrderResponse orderInfo, double paymentPrice, Double availableBalance) {
        PayApi.wxpay(mActivity, orderInfo.getSupplierId(), orderInfo.getUserId(), Utils.getUserLoginInfo().getUserAlias(), 0, paymentPrice, availableBalance, orderInfo.getOrderId(), orderInfo.getOrderNo(), new DialogCallback<WXPay>(mActivity, getString(R.string.get_wxpay_info)) {
            @Override
            public void onSuccess(WXPay pay, Call call, Response response) {
                WXPayUtils.payByWX(pay);

            }
        });
    }

    @Override
    protected FragmentAnimator onCreateFragmentAnimator() {
        return new DefaultHorizontalAnimator();
    }

    /**
     * 调用支付宝支付
     *
     * @param orderInfo 订单消息
     */
    private void invokeAliPay(MyOrderResponse orderInfo, double paymentPrice, Double availableBalance) {
        PayApi.alipay(mActivity, orderInfo.getSupplierId(), orderInfo.getUserId(), Utils.getUserLoginInfo().getUserAlias(), 0, paymentPrice, availableBalance, orderInfo.getOrderId(), orderInfo.getOrderNo(), new DialogCallback<String>(mActivity, getString(R.string.get_alipay_info)) {
            @Override
            public void onSuccess(String pay, Call call, Response response) {
                payByALi(pay);
            }
        });
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.view_address://有地址数据
                startReceiveAddress();
                break;
            case R.id.view_select_address://选择送货地址，没有默认地址情况
                if (haveAddress) {
                    startReceiveAddress();
                } else {//没有地址数据
                    start(ModifyAddressFragment.getInstance(false, null));
                }
                break;
            case R.id.view_invoice://发票
                start(InvoiceFragment.getInstance(invoice));
                break;
            case R.id.view_coupon://优惠券
                if (getString(R.string.get_error).equals(mCouponTicketTv.getText().toString())) {//加载错误
                    getCanUseCoupon();
                    return;
                }
                if (mCanUseCouponList.size() == 0) {
                    XToastUtils.showShortToast(getString(R.string.no_can_sue_coupon));
                    return;
                }
                showCouponDialog();
                break;
            case R.id.view_card:
                if (getString(R.string.get_error).equals(mCardTicketTv.getText().toString())) {
                    getMyRechargeCard();
                    return;
                }
                if (mCanUseCardList.size() == 0) {
                    XToastUtils.showShortToast(getString(R.string.no_card));
                    return;
                }
                showCardDialog();
                break;
            case R.id.tv_go_pay:

                //执行支付之前要对价格进行处理 邮费 优惠券 卡券等的处理  得到最后需要支付的价格
                //
                //如果需支付的价格为0 点击去付款 生成订单后跳转支付成功页面  价格不为0 采用支付方式进行支付

                if (finalPrice == 0) {
                    addOrder();
                } else {
                    if (mSelectPayMethodView.getPayMethod() != -1) {
                        //如果选择微信支付 先判断是否支付微信客户端支付 （是否支持支付版本 和 是否安装客户端）
                        if (mSelectPayMethodView.getPayMethod() != PayConfig.WX_PAY || (mSelectPayMethodView.getPayMethod() == PayConfig.WX_PAY && WXPayUtils.checkIsSupportWXPay(mActivity
                        ))) {
                            addOrder();
                        }
                    } else {
                        //                        XTipsDialog.showFail(mActivity, getString(R.string.please_select_pay_type));
                        XToastUtils.showShortToast(getString(R.string.please_select_pay_type));
                    }
                }

                break;
        }
    }

    /**
     * 跳转到地址列表
     */
    private void startReceiveAddress() {
        long addressId = -1;
        if (!CheckUtils.isNull(mAddress)) {
            addressId = mAddress.getAddressId();
        }
        start(ReceiveAddressFragment.getInstance(true, addressId));
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }

    @Override
    protected void onHandleEvent(EventManager eventManager) {
        super.onHandleEvent(eventManager);
        Address address = null;
        if (eventManager.getData() != null && eventManager.getData() instanceof Address) {
            address = (Address) eventManager.getData();
        }
        switch (eventManager.getEventCode()) {
            case LeEventCode.MSG_CODE_MODIFY_ADDRESS://修改地址
                if (address == null) {
                    return;
                }
                if (mAddress == null || address.getAddressId() == mAddress.getAddressId() || address.getIsDefault() == 1) {
                    mAddress = address;
                }
                ThreadPool.runOnUi(() -> getExpress(false, true));
                break;
            case LeEventCode.MSG_CODE_MODIFY_DEL_ADDRESS://删除地址
                if (address == null) {
                    return;
                }
                if (mAddress != null && address.getAddressId() == mAddress.getAddressId()) {
                    mAddress = null;
                }
                expressPrice = 0.00;
                activityPrice = tempActivityPrice;
                mActivityPrice.setAmount(activityPrice);//设置活动优惠价格
                mExpressPrice.setAmount(String.valueOf(expressPrice));
                //是否活动抵扣减号隐藏减号
                mActivityMinusTv.setVisibility(activityPrice == 0 ? View.GONE : View.VISIBLE);
                noLimitCouponCalculate();//重新计算优惠券抵扣
                calculateCardPriceDiscount();//重新计算卡券抵扣
                //重新计算价格
                calculateFinalPrice();
                break;
            case LeEventCode.MSG_CODE_MODIFY_SEL_ADDRESS://选择地址
                if (address == null) {
                    return;
                }
                mAddress = address;
                ThreadPool.runOnUi(() -> getExpress(false, false));
                break;

            case LeEventCode.MSG_CODE_PAY_SUCCESS:
                Utils.putLastPayType(PayConfig.WX_PAY);
                start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
                break;

            case LeEventCode.MSG_CODE_WX_PAY_CANCEL:
                ThreadPool.postOnUiDelayed(() -> cancelToDetail(), 10);
                break;

            case LeEventCode.MSG_CODE_BALANCE_PAY_CANCEL:
                //                XToastUtils.showShortToast(getString(R.string.pay_cancel));
                //                cancelToDetail();
                XTipsDialog.showFail(mActivity, getString(R.string.pay_cancel), () -> cancelToDetail());
                break;
            case LeEventCode.MSG_CODE_INVOICE://发票
                invoice = (InvoiceFragment.Invoice) eventManager.getData();
                mInvoiceTv.setText(invoice.type == -1 ? getString(R.string.invoice_not_need) : invoice.typeStr);
                break;
        }

        setAddressData();
    }

    /**
     * 弹出付款详情 对话框
     */
    private void showPayDetailDialog(int payType, double total, double balance, double needToPay, boolean state) {
        confirmPayDialog = new ConfirmPayDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.PAY_TYPE, payType);
        bundle.putDouble(IntentConfig.PAY_TOTAL_PRICE, total);
        bundle.putDouble(IntentConfig.PAY_AVAILABLE_BALANCE, balance);
        bundle.putDouble(IntentConfig.PAY_NEED_TO_PAY_PRICE, needToPay);
        bundle.putBoolean(IntentConfig.BALANCE_CHECKBOX_STATE, state);
        confirmPayDialog.setArguments(bundle);
        confirmPayDialog.setPayTypeSelectListener(new ConfirmPayDialog.OnMultiClickListener() {

            @Override
            public void onCheckChanged(AnimationCheckBox checkBox, boolean isChecked, double needToPay) {
                checkBoxState = isChecked;
                needToPayPrice = needToPay;
            }

            @Override
            public void onConfirmClick() {
                confirmPayDialog.dismiss();
                switch (mDialogPayType) {
                    case PayConfig.WX_PAY://微信支付
                        if (WXPayUtils.checkIsSupportWXPay(mActivity))
                            invokeWXPay(mAddedOrderInfo, total, balance);
                        break;
                    case PayConfig.ALI_PAY://支付宝
                        invokeAliPay(mAddedOrderInfo, total, balance);
                        break;
                }
            }

            @Override
            public void onPayTypeClick() {
                confirmPayDialog.dismiss();
                showSelectPayTypeDialog();
            }
        });
        confirmPayDialog.show(getFragmentManager(), "ConfirmPayDialog");
    }

    /**
     * 弹出选择支付方式对话框
     */
    private void showSelectPayTypeDialog() {
        payTypeSelectDialog = new PayTypeSelectDialog();
        Bundle bundle = new Bundle();
        bundle.putInt(IntentConfig.PAY_TYPE, mDialogPayType);
        payTypeSelectDialog.setArguments(bundle);
        payTypeSelectDialog.setPayTypeSelectListener(type -> {
            mDialogPayType = type;
            showPayDetailDialog(mDialogPayType, mAddedOrderInfo.getPaymentPrice(), mMyBalance.getAvailableBalance(), needToPayPrice, checkBoxState);
        });
        payTypeSelectDialog.show(getFragmentManager(), "PayTypeSelectDialog");
    }


    /**
     * 显示优惠券对话框
     */
    private void showCouponDialog() {
        if (mCanUseCouponList.size() == 0) {
            return;
        }
        if (mCouponDialog == null) {
            Bundle bundle = new Bundle();
            bundle.putParcelableArrayList(IntentConfig.COUPON_DATA, (ArrayList<? extends Parcelable>) mCanUseCouponList);
            mCouponDialog = new CouponDialog();
            mCouponDialog.setArguments(bundle);
        }
        mCouponDialog.show(getFragmentManager(), "coupon");
        mCouponDialog.setOnConfirmClickListener(new CouponDialog.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(int pos) {
                if (pos == -1) {//没有选择
                    couponsItemId = 0;
                    couponPrice = 0;
                    isNoLimitCoupon = false;
                } else {
                    CanUseCoupon canUseCoupon = mCanUseCouponList.get(pos);
                    if (canUseCoupon.getCouponsType() == 0) {
                        isNoLimitCoupon = true;
                        CLog.i("hcy", "isNoLimitCoupon=" + isNoLimitCoupon);
                    } else {
                        isNoLimitCoupon = false;
                    }
                    couponsItemId = canUseCoupon.getCouponsItemId();
                    couponPrice = getCouponPrice(canUseCoupon);//区分是金额还是折扣比例
                    if (isNoLimitCoupon) {
                        originalCouponPrice = couponPrice;
                    } else {
                        originalCouponPrice = 0;
                    }
                }

                StringBuilder builder = new StringBuilder();
                if (couponPrice == 0) {
                    //                    builder.append(couponPrice).append(getString(R.string.price_coupon));
                    builder.append("请选择");
                } else {
                    if (mCanUseCouponList.get(pos).getCouponsType() == 0) {
                        double price = getExcludeCouponFinalPrice();
                        builder.append(couponPrice).append(getString(R.string.price_coupon));
                        if (couponPrice >= price) {//大于支付价格
                            couponPrice = price;
                        }
                    } else {
                        double value = NumberUtlis.mul(mCanUseCouponList.get(pos).getCouponsVal(), 0.1);
                        builder.append(value).append(getString(R.string.discount_coupon));
                    }
                }
                mCouponTicketTv.setText(builder);
                mCouponPrice.setAmount(String.valueOf(couponPrice));

                totalPriceMatchShopFreePrice();//重新计算是否满足包邮
                calculateFinalPrice();
            }
        });

    }


    /**
     * 获取优惠的价格，因为要区分是价格优惠还是折扣优惠
     */
    private double getCouponPrice(CanUseCoupon coupon) {
        double couponPrice = 0;
        double totalPrice = 0.0;
        //区分CouponsLimit打折的约束 0 全店铺优惠 1 商品分类优惠 2 商品优惠 ,
        switch (coupon.getCouponsLimit()) {
            case 0://找出商品店铺id 与 优惠券店铺id相等的全部商品,总价格是否满足
                totalPrice = NumberUtlis.sub(goodTotalPrice, activityPrice);
                break;
            case 1://找出商品分类id 与 优惠券 couponsLimitNote 相等的全部商品，
                totalPrice = Utils.getTotalPriceByClassifyId(mGoodListData, coupon.getCouponsLimitNote());
                break;
            case 2:// 找出商品id 与 优惠券 couponsGoods 相等的全部商品，总价格是否满足
                totalPrice = Utils.getTotalPriceByGoodId(mGoodListData, coupon.getCouponsGoods());
                break;
        }
        couponPrice = coupon.getCouponsType() == 0 ? coupon.getCouponsVal() :
                NumberUtlis.mul(totalPrice, NumberUtlis.sub(1, NumberUtlis.mul(0.01, coupon.getCouponsVal())));//价格优惠还是打折优惠
        return couponPrice;
    }


    /**
     * 可用卡券
     */
    private void showCardDialog() {
        if (mCanUseCardList.size() == 0) {
            return;
        }
        Bundle bundle = new Bundle();
        bundle.putParcelableArrayList(IntentConfig.COUPON_DATA, (ArrayList<? extends Parcelable>) mCanUseCardList);
        bundle.putString(IntentConfig.CARD_ID_DATA, cardItemId);
        CardDialog mCardDialog = new CardDialog();
        mCardDialog.setArguments(bundle);

        mCardDialog.show(getFragmentManager(), "card");
        mCardDialog.setOnConfirmClickListener(new CardDialog.OnConfirmClickListener() {
            @Override
            public void onConfirmClick(String str, double amount, int size) {
                cardItemId = str;
                originalCardPrice = cardPrice = amount;
                StringBuilder builder = new StringBuilder(String.valueOf(amount));
                builder.append(String.format(getString(R.string.card_count), size));
                mCardTicketTv.setText(builder);
                calculateCardPriceDiscount();
                calculateFinalPrice();
            }
        });
    }

    /**
     * 计算卡券改变后的价格
     */
    private void calculateCardPriceDiscount() {
        double price = getExcludeCardFinalPrice();
        CLog.i("hcy", "------price----------=" + price);
        if (originalCardPrice >= price) {//大于支付价格
            cardPrice = price;
        }
        mCardPrice.setAmount(String.valueOf(cardPrice));
    }


    /**
     * 支付宝支付
     */
    private void payByALi(String payInfo) {
        //        String payParam = payInfo;//后台返回,签名看在本地还是服务器
        AliPayUtil aliPayUtil = AliPayUtil.createInstance(mActivity, payInfo);
        aliPayUtil.setPayCallBack(new IPayCallBack() {
            @Override
            public void paySuccess() {//支付成功
                XTipsDialog.showSuccess(mActivity, getString(R.string.pay_success), () -> {
                    start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
                    EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ALI_PAY_SUCCESS));
                    Utils.putLastPayType(PayConfig.ALI_PAY);
                });
                //                XToastUtils.showShortToast(getString(R.string.pay_success));
                //                start(PaySuccessFragment.getInstance(mAddedOrderInfo.getOrderId()));
                //
                //                EventBus.getDefault().post(new EventManager(LeEventCode.MSG_CODE_ALI_PAY_SUCCESS));
                //                Utils.putLastPayType(PayConfig.ALI_PAY);
            }

            @Override
            public void payFailed() {//支付失败
                //                XTipsDialog.showFail(mActivity, getString(R.string.pay_failed));
                XTipsDialog.showFail(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_failed), () -> cancelToDetail());
                //                XToastUtils.showShortToast(getString(R.string.pay_failed));
            }

            @Override
            public void payOnWaitForConfirm() {//结果等待确认
                XTipsDialog.showFail(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_wait_to_confirm));
                //                XToastUtils.showShortToast(getString(R.string.pay_wait_to_confirm));
            }

            @Override
            public void userCanceled() {
                XTipsDialog.showFail(mActivity, LeYaoGoApplication.getContext().getString(R.string.pay_cancel), () -> cancelToDetail());

            }
        });
        aliPayUtil.startToPay();
    }

    /**
     * 支付取消跳转至订单详情
     */
    private void cancelToDetail() {
        Bundle bundle = new Bundle();
        bundle.putLong("userId", Utils.getUserLoginInfo().getUserId());
        bundle.putLong("orderId", mAddedOrderInfo.getOrderId());
        Utils.startActivity(mActivity, OrderDetailActivity.class, bundle);
        mActivity.finish();
    }

    /**
     * 返回提示框
     */
    private void showCancelDialog() {
        CommonDialog dialog = CommonDialog.createTwoButton(getString(R.string.leave), getString(R.string.go_on),
                getString(R.string.coupon_not_wait));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                mActivity.onBackPressedSupport();
            }

            @Override
            public void right() {
                dialog.dismiss();
            }

            @Override
            public void middle() {
            }
        });
        dialog.show(getFragmentManager(), "confirm_leave");

    }

    /**
     * 充值提示框
     */
    private void showGoToChargeDialog() {
        CommonDialog dialog = CommonDialog.createTwoButton(getString(R.string.select_pay_type), getString(R.string.go_recharge), getString(R.string.yue_not_enough));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
                dialog.getDialog().setOnDismissListener(dialog1 -> cancelToDetail());
                dialog.dismiss();

            }

            @Override
            public void right() {
                dialog.getDialog().setOnDismissListener(dialog1 -> {
                    cancelToDetail();
                    Utils.startActivity(mActivity, BalanceActivity.class);
                });
                dialog.dismiss();

            }

            @Override
            public void middle() {

            }
        });
        dialog.show(getFragmentManager(), "recharge");
    }


    /**
     * 支付方式获取失败对话框
     */
    private void showGetPayWayFailDialog() {
        CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.sure), getString(R.string.get_pay_type_fail));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {


            }

            @Override
            public void right() {


            }

            @Override
            public void middle() {
                dialog.dismiss();
                mActivity.finish();
            }
        });
        dialog.show(getFragmentManager(), "getPayType");
    }

    /**
     * 地址不支持配送对话框
     */
    private void showAddressNotExpress() {
        CommonDialog dialog = CommonDialog.createSingleButton(getString(R.string.go_sel_address), getString(R.string.address_not_express));
        dialog.setOnButtonClickListener(new CommonDialog.OnButtonClickListener() {
            @Override
            public void left() {
            }

            @Override
            public void right() {
            }

            @Override
            public void middle() {
                startReceiveAddress();
                dialog.dismiss();
            }
        });
        dialog.show(getFragmentManager(), "address");
    }


    @Override
    public void leftContainerClick() {
        performanceEvent();
    }

    /**
     * 判断弹出提示框还是取消送货时间选择框
     */
    private void performanceEvent() {
        showCancelDialog();
    }


    @Override
    public boolean onBackPressedSupport() {
        performanceEvent();
        return true;
    }

}
